package com.wk.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;

@Component
public class RibbonFilter2 extends ZuulFilter {

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return RequestContext.getCurrentContext().sendZuulResponse();	//配合run方法里的setSendZuulResponse使用
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletRequest request = context.getRequest();

		//获取用户令牌
		String authorization = request.getHeader("Authorization");

		//解析令牌

		if (authorization.equals("service1")) {
			try {
				//设置服务id，参考yml中设置的service-id
				context.set(FilterConstants.SERVICE_ID_KEY,"service-id");

				//设置要转到的服务
				context.setRouteHost(new URI("http://localhost:8081/xx/xx").toURL());

				context.setSendZuulResponse(false);		//控制是否执行pre后面的过滤器，所有的pre过滤器还是会执行
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return null;
	}
}
